import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {ActivatedRoute, Router, Params} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {PostlistService} from './services/postlist.service';
import {Post} from '../model/post-model';
import {User} from "../../user/model/user-model";

@Component({
  selector: 'app-postlist',
  templateUrl: './postlist.component.html',
  styleUrls: ['./postlist.component.scss']
})
export class PostlistComponent implements OnInit {
  public itemsPerPage: number = 5;
  public totalRecords: number = 11;
  public currentPage: number = 1;
  public offset: number = 0;
  public end: number = 0;

  public searchText: string;
  public searchTextStream: Subject<string> = new Subject<string>();

  public postList: Array<Post>;

  public currentUser:User;

  constructor(public router: Router,
              public activeRoute: ActivatedRoute,
              public postService: PostlistService) {

  }

  ngOnInit() {
    this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
    //从路由里面获取URL参数
    this.activeRoute.params.subscribe(params => {
      console.log(params);
      this.currentPage = params.pageId;
      this.loadData(this.searchText);
    });

    this.searchTextStream
      .debounceTime(500)
      .distinctUntilChanged()
      .subscribe(searchText => {
        console.log(this.searchText);
        this.loadData(this.searchText)
      });
  }


  public loadData(searchText: string) {
    this.offset = (this.currentPage - 1) * this.itemsPerPage;
    this.end = (this.currentPage) * this.itemsPerPage;
    return this.postService.getPostList(searchText).subscribe(
      res => {
        //this.postList = res["posts"].slice(this.offset, this.end > this.totalRecords ? this.totalRecords : this.end);
        this.postList = res;
        this.totalRecords = this.postList.length;
        this.postList = this.postList.slice(this.offset,this.end > this.totalRecords ? this.totalRecords : this.end);
        console.log(this.totalRecords+'条记录');
      },
      error => {
        console.log(error)
      },
      () => {
      }
    );
  }

  public pageChanged(event: any): void {
    let temp = parseInt(event.page) + 1;
    this.router.navigateByUrl("posts/page/" + temp);
  }

  public searchChanged($event): void {
    this.searchTextStream.next(this.searchText);
  }

  public gotoWrite(): void {
    //TODO：如果没有登录，跳转到登录页，如果已登录，跳往写作页
    this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
    if(this.currentUser){//如果登录了就转到文章编辑页面
      this.router.navigateByUrl("user/write");
    }else {
      this.router.navigateByUrl('login')
    }

  }
}
